
function StarmapAssistant() {
	/** this is the creator function for your scene assistant object. It will be passed all the
	   additional parameters (after the scene name) that were passed to pushScene. The reference
	   to the scene controller (this.controller) has not be established yet, so any initialization
	   that needs the scene controller should be done in the setup function below. */
}
/**Sets up the scene for the starmap.
 */
StarmapAssistant.prototype.setup = function() {
	/* this function is for setup tasks that have to happen when the scene is first created */
	this.appController = Mojo.Controller.getAppController();
		
	/* use Mojo.View.render to render view templates and add them to the scene, if needed. */
	
	/* setup widgets here */
	this.controller.setupWidget(Mojo.Menu.commandMenu,
          this.lowerMenuAttributes = {},
          this.lowerMenuModel = {
		  	  visible: false,
              label: $L('Starmap Lower Menu'), 
								items: [{label: $L('Find My Sky'), command:'findme'}, 
										{icon: 'refresh', command:'reload'},
										/*
										{iconPath: 'images/menu-icon-minus.png', command:'zoomout'},
										{iconPath: 'images/menu-icon-plus.png', command:'zoomin'},
										*/
										]
     });
	 
	 this.controller.setupWidget('location-activity-spinner', 
	 	this.locationSpinnerAttributes = {spinnerSize: Mojo.Widget.spinnerLarge}, {});
		
	this.controller.setupWidget("skywindow",
         this.skywindowAttributes = {
             url:    'http://www.bmcstudiosllc.com/starmap/mobileapp_private/skywindow.html?zoom=18',
             //virtualpagewidth: this.controller.window.innerWidth,
             //virtualpageheight: this.controller.window.innerHeight,
			 useMouseEvents: true,
			 showClickedLink: false,
             },
         this.skywindowModel = {
             }
	);
	
	/* add event handlers to listen to events from widgets */
	this.handleLoadingProgress = this.handleLoadingProgress.bindAsEventListener(this);
	this.handleLoaded = this.handleLoaded.bindAsEventListener(this);
	Mojo.Event.listen(this.controller.get('skywindow'),Mojo.Event.webViewLoadProgress, this.handleLoadingProgress);
	Mojo.Event.listen(this.controller.get('skywindow'),Mojo.Event.webViewLoadStopped, this.handleLoaded);
}

/**Shows sky window
 *
 */
StarmapAssistant.prototype.activate = function(event) {
	/* put in event handlers here that should only be in effect when this scene is active. For
	   example, key handlers that are observing the document */
	  this.controller.setInitialFocusedElement(this.controller.get('skywindow'));
	  this.controller.get('location-activity-spinner').mojo.start()
}

/** remove any event handlers you added in activate and do any other cleanup that should happen before
	   this scene is popped or another scene is pushed on top */
StarmapAssistant.prototype.deactivate = function(event) {
	
}
/** this function should do any cleanup needed before the scene is destroyed as
	   a result of being popped off the scene stack */
StarmapAssistant.prototype.cleanup = function(event) {
	
}

/**Shows loading progress*/
StarmapAssistant.prototype.handleLoadingProgress = function(event) {
	this.controller.get("mainTitle").update('Loading: ' + event.progress + '%');
	/*
	if (event.progress > 5) {
		this.controller.get('skywindow').style.visibility = 'visible';
	}
	*/
}

/**Updates scene*/
StarmapAssistant.prototype.handleLoaded = function(event) {
	this.controller.get('overlay-scrim').hide();
	this.controller.get('location-activity-spinner').mojo.stop();
	this.controller.get("mainTitle").update('Starmap Mobile: Starmap');
	this.lowerMenuModel.visible = true;
	this.controller.modelChanged(this.lowerMenuModel);
}

/*
StarmapAssistant.prototype.zoomIn = function(event) {
	if (this.skywindowZoom < 18) {
		this.skywindowZoom++;
		this.controller.get('skywindow').mojo.openURL('javascript:void(cur_value=' + this.skywindowZoom);
	}
}

StarmapAssistant.prototype.zoomOut = function(event) {
	if (this.skywindowZoom > 1) {
		this.skywindowZoom--;
		this.controller.get('skywindow').mojo.openURL('javascript:void(cur_value=' + this.skywindowZoom);
	}
}
*/

/**Handles given commands.*/
StarmapAssistant.prototype.handleCommand = function(event) {
	if(event.type == Mojo.Event.command) {
		switch (event.command) {
			case 'findme':
				this.lowerMenuModel.items[0].command = 'disabled';
				this.controller.get('overlay-scrim').show();
				this.controller.get('location-activity-spinner').mojo.start();
				this.lowerMenuModel.visible = false;
				this.controller.modelChanged(this.lowerMenuModel);
				this.findMeButton();
				break;

			case 'reload':
				this.controller.get('skywindow').mojo.reloadPage();
				break;
				
			/*
			case 'zoomout':
				this.zoomOut();
				break;
				
			case 'zoomin':
				this.zoomIn();
				break;
			*/
		}
	}
}

/**   Updates the location for the scene.
 */
StarmapAssistant.prototype.locationCallback = function(data) {
	var locationResponse;
	switch (data.errorCode) {
					case 0:
						locationResponse = "Latitude: " + data.latitude + "\n" + "Longitude: " + data.longitude;
						break;
					case 1:
						locationResponse = "GPS Timeout.";
						break;
					case 2:
						locationResponse = "Position Unavailable.";
						break;
					case 5:
						locationResponse = "Location services are turned off.";
						break;					
					default:
						locationResponse = "Location error: " + data.errorCode;
						break;
				}
				this.controller.get('overlay-scrim').hide();
				this.controller.get('location-activity-spinner').mojo.stop();
				this.lowerMenuModel.visible = true;
				this.controller.modelChanged(this.lowerMenuModel);
				this.controller.showAlertDialog({
				    title: $L("Find My Sky Dialog"),
				    message: $L(locationResponse),
					choices:[{label:$L('Ok')}]
				});
				if (data.errorCode==0) {
					var locationURL = this.getURL(data);
					this.controller.get('skywindow').mojo.openURL(locationURL);
				};
				this.lowerMenuModel.items[0].command = 'findme';
}

/**Queries the palm database for location.*/

StarmapAssistant.prototype.findMeButton = function(event) {
	this.controller.serviceRequest('palm://com.palm.location', {
		method:"getCurrentPosition",
		parameters:{accuracy: 'Medium', maximumAge: 10, responseTime: 1},
		onSuccess: function( data ) 
			{
				this.locationCallback(data);
			}.bind(this),
		onFailure: function( data )
			{
				this.locationCallback(data);
			}.bind(this),
		}
	);
}

/**URL Functions*/
StarmapAssistant.prototype.getURL = function(UI){
	var RA = this.locateSkyAbove(UI.latitude,UI.longitude);
    var DEC = UI.latitude;
    var url = "http://www.bmcstudiosllc.com/starmap/mobileapp_private/skywindow.html?";
    //if (UI.angle){DEC=this.updateDec(DEC,UI.angle);}
    url=url+"RA="+RA + "&DE="+DEC+"&zoom=8";
    return url;
}

/** Updates declination due to angle.
 * @param declination Current declination.
 * @param angle Current angle from horizon.
 * @return newDec The new declination based on angle.
 */
StarmapAssistant.prototype.updateDec = function(declination, angle){
	return (declination-(angle/100));
}

/** Finds the celestial coordinates for the sky above the user.
 * @param latt Current latitude.
 * @param lonn Current longitude.
 * @return newRA The new right ascension given latitude and longitude.
 */
StarmapAssistant.prototype.locateSkyAbove = function(latt, lonn)
{
	var skyLat=latt;
	var skyLon=lonn;
	var time;
	var timeZone;
	if(skyLat&&skyLon)
    {
        var lat=parseFloat(skyLat);
        var lon=parseFloat(skyLon);
        var time=new Date();
        var timeZone=parseFloat(time.getTimezoneOffset()/60);
        var newRA=this.sidereal_time(time.getYear(),time.getMonth(),time.getDate(),time.getHours(),time.getMinutes(),time.getSeconds(),'SIDEREAL_LAST',lon);
        newRA+=timeZone;
        if(newRA<0)
            newRA+=24;
        else if(newRA>=24)
            newRA-=24;

        return newRA;
    }
    return 0;

}
/** Finds sidereal time compared to Grenich.
 */
StarmapAssistant.prototype.sidereal_time = function(time_now_tm_year,time_now_tm_mon,time_now_tm_day,time_now_tm_hour,time_now_tm_min,time_now_tm_sec,type,longitude)
{
        var JD_J2000,JD_now,JD_diff;
        var gmst,gast,JC,eqtime,last,lmst;
        time_ref_tm_sec=0;
        time_ref_tm_min=0;
        time_ref_tm_hour=12;
        time_ref_tm_day=1;
        time_ref_tm_mon=0;
        time_ref_tm_year=100;
        JD_J2000=this.julian_date(time_ref_tm_year,time_ref_tm_mon,time_ref_tm_day,time_ref_tm_hour,time_ref_tm_min,time_ref_tm_sec);
        JD_now=this.julian_date(time_now_tm_year,time_now_tm_mon,time_now_tm_day,time_now_tm_hour,time_now_tm_min,time_now_tm_sec);
        JD_diff=JD_now-JD_J2000;
        JC=JD_diff/36525.0;
        gmst=280.46061837+360.98564736629*JD_diff+0.0003887933*Math.pow(JC,2)-Math.pow(JC,3)/38710000.0;
        while(gmst>=360.0)
            gmst-=360.0;
        gmst=gmst/15.0;
        if(type=='SIDEREAL_GMST')
            return(gmst);
        var day_of_year=this.FDoY(time_now_tm_year,time_now_tm_mon+1,time_now_tm_day);
        eqtime=(-0.49+0.3*day_of_year/365.0+0.07*Math.cos(2.0*6.2831853*(day_of_year-35.0)/365.0))/3600.0;
        gast=gmst+eqtime;
        while(gast>24.0)
            gast-=24.0;
        if(type=='SIDEREAL_GAST')
            return gast;
        last=gast+24.0+longitude/15.0;
        while(last>24.0)
            last-=24.0;
        if(type=='SIDEREAL_LAST')
            return last;
        lmst=gmst+24.0+longitude/15.0;
        while(lmst>24.0)
            lmst-=24.0;
        if(type=='SIDEREAL_LMST')
            return lmst;
        return lmst;
    }
    /** Finds current Julian date for the day.
    * @return JD Today's Julian Date
    */
StarmapAssistant.prototype.julian_date = function(now_time_tm_year,now_time_tm_mon,now_time_tm_day,now_time_tm_hour,now_time_tm_min,now_time_tm_sec)
{
    var year=now_time_tm_year;
    var month=now_time_tm_mon+1;
    var day=now_time_tm_day;
    var UT=now_time_tm_hour+now_time_tm_min/60.0+now_time_tm_sec/3600.0;
    var JD=367*year-this.toInt(7.0*(year+this.toInt((month+9.0)/12.0))/4.0)-
        this.toInt(3.0*(this.toInt((year+(month-9.0)/7.0)/100.0)+1.0)/4.0)+
        this.toInt(275.0*month/9.0)+day+1721028.5+UT/24.0;
    return(JD);
}
/** Converts input to integer.
 * @param nmb Any number.
 * @return nmb The given number as an integer.
 */
StarmapAssistant.prototype.toInt = function(nmb)
{
    if(nmb>0)
        return Math.floor(nmb);
    if(nmb<0)
        return Math.ceil(nmb);
    return nmb;
}
/** Finds the day of the year
 * @param Y year
 * @param M month
 * @param D day
 * @return The day of the year in seconds from the first of the year
 */
StarmapAssistant.prototype.FDoY = function(Y,M,D)
{
    return(Date.UTC(Y,M,D)-Date.UTC(Y,1,1))/86400000+1;
}